/*
 * import {loadCityLib}  from '../lib/ktrainCity';
 * loadCityLib({prnTid: '#city', tag: '.from', from: fromTagVal, to: toTagVal});
 * prnTid 父元素
 * tag 点击的当前元素：目的地或者出发地
 * from 出发地的值
 * to 目的地的值
 * */

import {Slider, sliderHide, sliderShow} from '../lib/kslider';
import {getTrainCityFun, isArrContain} from '../util/aid';

const $ = require('../lib/kdom');
const keyArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const hostCityArr = [
  {"Id": 3, "StationName": "北京", "StationCode": "BJP", "StationShortName": "bji", "StationFullName": "beijing"}
  , {"Id": 11, "StationName": "上海", "StationCode": "SHH", "StationShortName": "sha", "StationFullName": "shanghai"}
  , {"Id": 40, "StationName": "杭州", "StationCode": "HZH", "StationShortName": "hzh", "StationFullName": "hangzhou"}
  , {"Id": 30, "StationName": "广州", "StationCode": "GZQ", "StationShortName": "gzh", "StationFullName": "guangzhou"}
  , {"Id": 52, "StationName": "南京", "StationCode": "NJH", "StationShortName": "nji", "StationFullName": "nanjing"}
  , {"Id": 24, "StationName": "成都", "StationCode": "CDW", "StationShortName": "cdu", "StationFullName": "chengdu"}
  , {"Id": 67, "StationName": "西安", "StationCode": "XAY", "StationShortName": "xan", "StationFullName": "xian"}
  , {"Id": 71, "StationName": "郑州", "StationCode": "ZZF", "StationShortName": "zzh", "StationFullName": "zhengzhou"}
  , {"Id": 8, "StationName": "重庆", "StationCode": "CQW", "StationShortName": "cqi", "StationFullName": "chongqing"}
  , {"Id": 34, "StationName": "合肥", "StationCode": "HFH", "StationShortName": "hfe", "StationFullName": "hefei"}
  , {"Id": 188, "StationName": "汉口", "StationCode": "HKN", "StationShortName": "hko", "StationFullName": "hankou"}
  , {"Id": 63, "StationName": "武汉", "StationCode": "WHN", "StationShortName": "wha", "StationFullName": "wuhan"}
  , {"Id": 25, "StationName": "长沙", "StationCode": "CSQ", "StationShortName": "csh", "StationFullName": "changsha"}
  , {"Id": 405, "StationName": "武昌", "StationCode": "WCN", "StationShortName": "wch", "StationFullName": "wuchang"}
  , {"Id": 62, "StationName": "太原", "StationCode": "TYV", "StationShortName": "tyu", "StationFullName": "taiyuan"}
  , {"Id": 376, "StationName": "苏州", "StationCode": "SZH", "StationShortName": "szh", "StationFullName": "suzhou"}
  , {"Id": 439, "StationName": "厦门", "StationCode": "XMS", "StationShortName": "xme", "StationFullName": "xiamen"}
  , {"Id": 51, "StationName": "南昌", "StationCode": "NCG", "StationShortName": "nch", "StationFullName": "nanchang"}
  , {"Id": 57, "StationName": "沈阳", "StationCode": "SYT", "StationShortName": "sya", "StationFullName": "shenyang"}
  , {"Id": 16, "StationName": "天津", "StationCode": "TJP", "StationShortName": "tji", "StationFullName": "tianjin"}
  , {"Id": 375, "StationName": "深圳", "StationCode": "SZQ", "StationShortName": "szh", "StationFullName": "shenzhen"}
]

function loadTrainCityLib(options) {
  getTrainCityFun(function (rs) {
    // console.log('首页：', rs);
    initCity(rs, options);
  });
}

function initCity(data, options) {
  options = options || {};
  let rc = `<header class="bar bar-nav thame-danger"><div class="icon icon-left pull-left" id="cityClose"></div><h1 class="title">选择城市</h1><span class="icon pull-right" id="searchCityCancel" style="font-size:.75rem;display: none;">取消</span></header>
            <div class="hotkey" style="top: 4.4rem;">
                <div id="hotkey" class="hotkey-item">
                    ${getHotKey()}
                </div>
            </div>
            <div class="bar bar-header-secondary">
              <div class="searchbar active">
                <div class="search-input">
                  <label class="icon icon-search text-disabled" for="search"></label>
                  <input type="search" id='searchCity' placeholder='输入关键字...'/>
                </div>
                <a class="searchbar-cancel" id="searchCityBtn">搜索</a>
              </div>
            </div>
            <div class="content">
                <div class="city-container" id="blurQueryBox"></div>
                <div class="city-container" id="cityContainer">
                    ${createCity(data, options)}
                </div>
            </div>`;
  // console.log(rc);
  new Slider({content: rc});
  cityClose.onclick = () => {
    sliderHide();
  };
  selectCitySite();
}

function getHotKey() {
  let rc = '';
  for (let i = 0, len = keyArr.length; i < len; i++) {
    rc += `<a href="#jump-${keyArr[i].toLowerCase()}">${keyArr[i]}</a>`;
  }
  return rc;
}

function createCity(data, opt) {
  let opts = {'prnTid': opt.prnTid, 'tag': opt.tag};
  let rc = '';
  let hostCityStr = '';
  let allCity = '';//全部的站点列表
  if (data) {
    let bindClick = null;
    let className = '';
    let cityCode = null;
    let cityNmae = null;

    for (let i = 0, d1 = hostCityArr, d1Len = d1.length; i < d1Len; i++) {
      /*判断已选中的城市*/
      if (opt.from == d1[i]['StationCode'] || opt.to == d1[i]['StationCode']) {
        className = 'active';
      } else {
        className = '';
        cityCode = d1[i].StationCode;
        cityNmae = d1[i].StationName;
      }
      hostCityStr += `<a class="city-item ${className}" data-city='${cityCode},${cityNmae}' data-opt='${JSON.stringify(opts)}'>${cityNmae}</a>`;
    }
    for (let i = 0, d = keyArr, keyLen = d.length; i < keyLen; i++) {
      allCity = '';
      //获得城市
      for (let j = 0, o = data, len = o.length; j < len; j++) {
        /*判断已选中的城市*/
        if (opt.from == o[j]['StationCode'] || opt.to == o[j]['StationCode']) {
          className = 'active';
        } else {
          className = '';
          cityCode = o[j].StationCode;
          cityNmae = o[j].StationName;
        }
        /*全部城市*/
        if (o[j]['StationFullName'].toUpperCase().indexOf(d[i]) === 0) {
          allCity += `<a class="city-item ${className}" data-city='${cityCode},${cityNmae}' data-opt='${JSON.stringify(opts)}'>${cityNmae}</a>`;
        }
      }
      // 排序 A、B、C、...
      if (i < keyLen) {
        if (allCity) {
          rc += `<h4 class="city-title" id="jump-${d[i].toLowerCase()}">${d[i]}</h4>`;
        }
      }
      rc += allCity;
      /*j*/
    }
    /*i*/
  }
  return `<h4 class="city-title">热门城市</h4>${hostCityStr}${rc}`;
}

/*window.selectCity = (cityCode, cityNmae, opt) => {
 // console.log(cityCode, cityNmae, opt);
 let tag = null;
 if (opt.prnTid)
 tag = $.qu(`${opt.prnTid} ${opt.tag}`);
 else
 tag = $.qu(opt.tag);
 if (tag) {
 $.html(tag, cityNmae);
 tag.setAttribute('data-Code', cityCode);
 }
 sliderHide();
 };*/
// 选择在站点
function selectCitySite() {
  let tag = null;
  let tagAddr = null;
  let dataCity = null;
  let opt = null;
  cityContainer.addEventListener('click', function (e) {
    // e.target是被点击的元素!
    // 如果被点击的是A元素
    tag = e.target;
    if (tag && tag.nodeName == 'A') {
      dataCity = tag.getAttribute('data-city').split(',');
      opt = JSON.parse(tag.getAttribute('data-opt'));
      if (opt.prnTid)
        tagAddr = $.qu(`${opt.prnTid} ${opt.tag}`);
      else
        tagAddr = $.qu(opt.tag);
      if (tagAddr) {
        $.html(tagAddr, dataCity[1]);
        tagAddr.setAttribute('data-city', tag.getAttribute('data-city'));
      }
      sliderHide();
      // console.log(dataCity);
      // console.log(opt);
    }
  });

  blurQueryBox.addEventListener('click', function (e) {
    // e.target是被点击的元素!
    // 如果被点击的是A元素
    tag = e.target;
    if (tag && tag.nodeName == 'A') {
      dataCity = tag.getAttribute('data-city').split(',');
      opt = JSON.parse(tag.getAttribute('data-opt'));
      if (opt.prnTid)
        tagAddr = $.qu(`${opt.prnTid} ${opt.tag}`);
      else
        tagAddr = $.qu(opt.tag);
      if (tagAddr) {
        $.html(tagAddr, dataCity[1]);
        tagAddr.setAttribute('data-city', tag.getAttribute('data-city'));
      }
      sliderHide();
      // console.log(dataCity);
      // console.log(opt);
    }
  });
}

export {loadTrainCityLib};
